﻿using IServices;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Models.Dtos;
using Models.DbModels;
using Common.Helper;
using Common.AuthHelper;
using Microsoft.AspNetCore.Authorization;

namespace SqlSugarDemo.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class AuthController : ControllerBase
    {
        readonly IUserServices _userServices;
        readonly IBindUserRoleServices _bindUserRoleServices;
        public AuthController(IUserServices userServices,IBindUserRoleServices bindUserRoleServices)
        {
            this._userServices = userServices;
            this._bindUserRoleServices = bindUserRoleServices;
        }
        [AllowAnonymous]
        [Route("Login"),HttpPost]
        public async Task<IActionResult> Login([FromBody] LoginDto info)
        {
            //判断用户和密码
            //用户名和密码
            var user = await _userServices.GetSingleAsync(it => it.Code == info.Code);
            if (user == null)
            {
                return Ok("没这个人");
            }
            if (user.Password != MD5Helper.MD5Encrypt32(info.Password))
            {
                return Ok("密码错误");
            }

            
            var jwt = new JwtToken();
            var roleList = await _bindUserRoleServices.GetRolesAsync(user.Id);
            
            jwt.UserName = user.Name;
            jwt.UserId = user.Id.ToString();
            jwt.RoleList = roleList;
            //foreach (var role in roleList)
            //{
            //    jwt.RoleList.Add(role);
            //}
           
            var token = JwtHelper.CreateToken(jwt);
            var Rtoken = JwtHelper.CreateRToken(jwt);
            return Ok(new{
                token = token,
                rtoken = Rtoken
            });
        }

        [AllowAnonymous]
        [Route("RToken"), HttpPost]
        public async Task<IActionResult> RToken([FromForm] string rtoken)
        {
            var jwt =  JwtHelper.GetRTokenValue(rtoken);
                 var user = await _userServices.GetByIdAsync(jwt.UserId);
            //var jwt = new JwtToken();
            var roleList = await _bindUserRoleServices.GetRolesAsync(user.Id);

            jwt.UserName = user.Name;
            jwt.UserId = user.Id.ToString();
            jwt.RoleList = roleList;
            //foreach (var role in roleList)
            //{
            //    jwt.RoleList.Add(role);
            //}

            var token = JwtHelper.CreateToken(jwt);
            return Ok(new
            {
                token = token,
                rtoken = rtoken
            });
        }
    }
}
